import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)



// 引入路由所映射的组件
import Login from '@/views/login.vue'
import { Toast } from 'vant'

//个人中心
// import Personal from '@/views/personal.vue'

// 创建路由对象
let router = new VueRouter({
    // 配置路由
    routes: [
        {
            name: 'login',
            path: '/login',
            component: Login
        },
        {
            name: 'personal',
            path: '/personal/:id',
            component: () => import('@/views/personal.vue')
        },
        {
            name: 'edit_profile',
            path: '/edit_profile/:id',
            component: () => import('@/views/edit_profile.vue')
        },

        //用户注册
        {
            name: 'register',
            path: '/register',
            component: () => import('@/views/register.vue')
        },
        {
            name: 'default',
            path: '/',
            redirect: { name: 'index' }
        }, {
            name: 'index',
            path: '/index',
            component: () => import('@/views/index.vue')
        },
        // 新闻详情
        {
            name: 'articleDetail',
            path: '/articleDetail/:id',
            component: () => import('@/views/articleDetail.vue')
        },
        {
            name: 'myfollows',
            path: '/myfollows',
            component: () => import('@/views/myFollows.vue')
        },
        //我的收藏
        {
            name: 'mystar',
            path: '/mystar',
            component: () => import('@/views/myStars.vue')
        },
        //评论
        {
            name: 'comment',
            path: '/comment/:id',
            component: () => import('@/views/comments.vue')
        },
        //栏目管理页面得渲染
        {
            name: 'CateManager',
            path: '/cateManager',
            component: () => import('@/views/cateManager.vue')
        }
        ,
        //搜索栏目
        {
            name: 'search',
            path: '/search',
            component: () => import('@/views/search.vue')
        }


    ]
})

// 添加导航守卫:前置守卫：在跳转之前进行调用
// 所有路由跳转请求都会经过这个导航守卫
// to:目标路由
// from:源路由
// next:下一步的操作，就是用户当前需要进行的操作

router.beforeEach((to, from, next) => {
    // 并不是每个页面的访问都需要先登陆,同时这里需要获取用户登录的时候token值

    //这里是需要判断是否跳到个人中心页面
    if (to.name == 'personal' || to.name == 'edit_profile') {
        // let token = localStorage.getItem('token')
        // if (token) {
        //     next()
        let token = localStorage.getItem('token')
        if (token) {
            next()
        } else {
            Toast('请先登陆')
            // 说明没有登陆，则重定向到登陆页
            next({ next: 'login' })
        }
    } else {
        next()
    }

})


// 暴露
export default router